/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-10-16 08:25:08
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-16 08:27:59
 * @FilePath: /react18-vite-admin/src/service/biz/role/useRoleDetail.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */


import { useState } from 'react';

import { useStateRef } from '@/service/useStateRef';
import type { RoleDetial } from '@/typings/api/role';
import { readRoleDetail, createOrUpdateRole, RoleParam } from '@/api/role';

export { RoleParam };

export const useRoleDetail = () => {
    const [detail, setDetail] = useState<RoleDetial>();
    const [loading, loadingRef, setLoading] = useStateRef(false);

    const getDetail = (id: number) => {
        if (loadingRef.current) return;
        setLoading(true);
        return readRoleDetail(id)
            .then((res) => {
                setDetail(res.data);
                return res;
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const [saveLoading, saveLoadingRef, setSaveLoading] = useStateRef(false); 
    const saveRole = (param: RoleParam) => {
        console.log(param);
        if (saveLoadingRef.current) return Promise.reject();
        setSaveLoading(true);
        return createOrUpdateRole(param).finally(() => {
            setSaveLoading(false);
        });
    };

    return {
        detail,
        loading,
        getDetail,
        saveLoading,
        setSaveLoading,
        saveRole
    };
}
